﻿using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.OpenApi.Models;
using Ebusiness_WebSites.Data;
using Ebusiness_WebSites.Localization;
using Volo.Abp;
using Volo.Abp.Uow;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc.Localization;
using Volo.Abp.AspNetCore.Serilog;
using Volo.Abp.Autofac;
using Volo.Abp.AutoMapper;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.MySQL;
using Volo.Abp.Localization;
using Volo.Abp.Localization.ExceptionHandling;
using Volo.Abp.Modularity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Swashbuckle;
using Volo.Abp.Security.Claims;
using Volo.Abp.UI.Navigation.Urls;
using Volo.Abp.Validation.Localization;
using Volo.Abp.VirtualFileSystem;
using Volo.Abp.Http.Client;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Caching;
using Volo.Abp.Caching.StackExchangeRedis;
using Volo.Abp.AspNetCore.Mvc.AntiForgery;
using Ebusiness_OrderService.Services;
using Ebusiness_ProductService.Services;
using Volo.Abp.Http.Client.IdentityModel;
using Ebusiness_Authservice.Services;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;

namespace Ebusiness_WebSites;

[DependsOn(
    // ABP Framework packages
    typeof(AbpAspNetCoreMvcModule),
    typeof(AbpAutofacModule),
    typeof(AbpAutoMapperModule),
    typeof(AbpEntityFrameworkCoreMySQLModule),
    typeof(AbpSwashbuckleModule),
    typeof(AbpAspNetCoreSerilogModule),
    typeof(AbpHttpClientModule)
    , typeof(AbpCachingStackExchangeRedisModule)

#region 分布式权限系统  openddict 需要集成的应用模块
//, typeof(AbpHttpClientIdentityModelModule) // 集成Volo.Abp.Http.Client.IdentityModel
#endregion
)]
public class Ebusiness_WebSitesModule : AbpModule
{
    /* Single point to enable/disable multi-tenancy */
    private const bool IsMultiTenant = true;

    public override void PreConfigureServices(ServiceConfigurationContext context)
    {
        context.Services.PreConfigure<AbpMvcDataAnnotationsLocalizationOptions>(options =>
        {
            options.AddAssemblyResource(
                typeof(Ebusiness_WebSitesResource)
            );
        });
    }

    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        var hostingEnvironment = context.Services.GetHostingEnvironment();
        var configuration = context.Services.GetConfiguration();

        //配置自定义控制器
        ConfigurControllers(context);
        ConfigureAuthentication(context);
        //ConfigureMultiTenancy();
        ConfigureUrls(configuration);
        ConfigureAutoMapper(context);
        ConfigureSwagger(context.Services, configuration);
        ConfigureAutoApiControllers();
        //ConfigureVirtualFiles(hostingEnvironment);
        //ConfigureLocalization();
        ConfigureCors(context, configuration);
        //ConfigureDataProtection(context);
        ConfigureEfCore(context);
        //配置动态代理客户端
        ConfigHttpClient(context);
        //配置redis缓存
        CondfigRedisCache(context);
        //关闭xss攻击
        ConfigAntiforgery();
        //配置 Openiddict
        ConfigOpeniddict(context);
    }

    /// <summary>
    /// 配置 Openiddict
    /// </summary>
    private void ConfigOpeniddict(ServiceConfigurationContext context)
    {
        #region 配置作废
        {
            //// 配置身份认证
            //context.Services.AddAuthentication(options =>
            //{
            //    options.DefaultScheme = "Cookies";
            //    options.DefaultChallengeScheme = "oidc";
            //})
            //.AddCookie("Cookies")
            //.AddOpenIdConnect("oidc", options =>
            //{
            //    options.Authority = "https://localhost:44392";  //指向授权服务器（OpenIddict/IdentityServer4/Keycloak 等），告诉客户端去哪里获取 token。
            //    options.ClientId = "website";   //表明这是哪个客户端（电商网站）。
            //    options.ClientSecret = "123456";   
            //    options.ResponseType = OpenIdConnectResponseType.Code;   //明确使用 授权码模式（比隐式模式更安全）
            //    options.SaveTokens = true;  //把 AccessToken/RefreshToken 等保存到用户的 Cookie，会话期间可以直接使用。
            //    options.GetClaimsFromUserInfoEndpoint = true;  //OIDC 登录完成后，还会调用 UserInfo Endpoint 把用户信息（比如 sub、email、name）拉到本地 ClaimsPrincipal
            //    options.Scope.Add("OrderService");   //请求访问资源
            //    options.Scope.Add("offline_access");  //表示需要 刷新令牌（Refresh Token），支持长时间免登录
            //});

            //// 添加HTTP客户端工厂
            //context.Services.AddHttpClient();
        }
        #endregion
    }

    /// <summary>
    /// 关闭xss攻击
    /// </summary>
    private void ConfigAntiforgery()
    {
        Configure<AbpAntiForgeryOptions>(option =>
        {
            option.AutoValidate = false;
        });
    }

    /// <summary>
    /// 配置动态代理客户端
    /// </summary>
    /// <param name="context"></param>
    public void ConfigHttpClient(ServiceConfigurationContext context)
    {
        //配置全局动态客户端代理 (网关)
        context.Services.AddHttpClientProxies(typeof(Ebusiness_WebSitesModule).Assembly, "GetWay");

        ////配置订单 
        //context.Services.AddHttpClientProxy<IOrderService>("Ebusiness_OrderService");

        ////配置商品
        //context.Services.AddHttpClientProxy<IProductService>("Ebusiness_ProductService");

        ////配置鉴权服务
        //context.Services.AddHttpClientProxy<ITestService>("Ebusiness_AuthService");
    }

    private void ConfigureAuthentication(ServiceConfigurationContext context)
    {
        context.Services.Configure<AbpClaimsPrincipalFactoryOptions>(options =>
        {
            options.IsDynamicClaimsEnabled = true;
        });
    }

    /// <summary>
    /// 配置redis缓存
    /// </summary>
    /// <param name="context"></param>
    private void CondfigRedisCache(ServiceConfigurationContext context)
    {
        // 可选，设置统一前缀
        Configure<AbpDistributedCacheOptions>(options =>
        {
            options.KeyPrefix = "YourApp:"; // 可选，设置统一前缀
        });
    }

    private void ConfigureMultiTenancy()
    {
        Configure<AbpMultiTenancyOptions>(options =>
        {
            options.IsEnabled = IsMultiTenant;
        });
    }

    private void ConfigureUrls(IConfiguration configuration)
    {
        Configure<AppUrlOptions>(options =>
        {
            options.Applications["MVC"].RootUrl = configuration["App:SelfUrl"];
            options.RedirectAllowedUrls.AddRange(configuration["App:RedirectAllowedUrls"]?.Split(',') ?? Array.Empty<string>());

        });
    }

    /// <summary>
    /// 配置自定义控制器
    /// </summary>
    private void ConfigurControllers(ServiceConfigurationContext context)
    {
        //配置自定义过滤器
        context.Services.AddControllers(option =>
        {
            //添加自定义过滤器
            //option.Filters.Add<UnitOfWorkFilter>();
            //全局取消默认token校验 忽略xss攻击
            //option.Filters.Add(new IgnoreAntiforgeryTokenAttribute());
        });
        //servicesout configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
        context.Services.AddEndpointsApiExplorer();
    }

    private void ConfigureLocalization()
    {
        Configure<AbpLocalizationOptions>(options =>
        {
            options.Resources
                .Add<Ebusiness_WebSitesResource>("en")
                .AddBaseTypes(typeof(AbpValidationResource))
                .AddVirtualJson("/Localization/Ebusiness_WebSites");

            options.DefaultResourceType = typeof(Ebusiness_WebSitesResource);

            options.Languages.Add(new LanguageInfo("en", "en", "English"));
            options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
            options.Languages.Add(new LanguageInfo("ar", "ar", "العربية"));
            options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
            options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)"));
            options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar"));
            options.Languages.Add(new LanguageInfo("fi", "fi", "Finnish"));
            options.Languages.Add(new LanguageInfo("fr", "fr", "Français"));
            options.Languages.Add(new LanguageInfo("hi", "hi", "Hindi"));
            options.Languages.Add(new LanguageInfo("is", "is", "Icelandic"));
            options.Languages.Add(new LanguageInfo("it", "it", "Italiano"));
            options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
            options.Languages.Add(new LanguageInfo("ro-RO", "ro-RO", "Română"));
            options.Languages.Add(new LanguageInfo("ru", "ru", "Русский"));
            options.Languages.Add(new LanguageInfo("sk", "sk", "Slovak"));
            options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
            options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
            options.Languages.Add(new LanguageInfo("de-DE", "de-DE", "Deutsch"));
            options.Languages.Add(new LanguageInfo("es", "es", "Español"));
            options.Languages.Add(new LanguageInfo("el", "el", "Ελληνικά"));
        });

        Configure<AbpExceptionLocalizationOptions>(options =>
        {
            options.MapCodeNamespace("Ebusiness_WebSites", typeof(Ebusiness_WebSitesResource));
        });
    }

    private void ConfigureVirtualFiles(IWebHostEnvironment hostingEnvironment)
    {
        Configure<AbpVirtualFileSystemOptions>(options =>
        {
            options.FileSets.AddEmbedded<Ebusiness_WebSitesModule>();
            if (hostingEnvironment.IsDevelopment())
            {
                /* Using physical files in development, so we don't need to recompile on changes */
                options.FileSets.ReplaceEmbeddedByPhysical<Ebusiness_WebSitesModule>(hostingEnvironment.ContentRootPath);
            }
        });
    }

    private void ConfigureAutoApiControllers()
    {
        Configure<AbpAspNetCoreMvcOptions>(options =>
        {
            options.ConventionalControllers.Create(typeof(Ebusiness_WebSitesModule).Assembly);
        });
    }

    private void ConfigureSwagger(IServiceCollection services, IConfiguration configuration)
    {
        services.AddAbpSwaggerGenWithOAuth(
            configuration["AuthServer:Authority"]!,
            new Dictionary<string, string>
            {
                    {"Ebusiness_WebSites", "Ebusiness_WebSites API"}
            },
            options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo { Title = "Ebusiness_WebSites API", Version = "v1" });
                options.DocInclusionPredicate((docName, description) => true);
                options.CustomSchemaIds(type => type.FullName);
            });
    }

    private void ConfigureAutoMapper(ServiceConfigurationContext context)
    {
        context.Services.AddAutoMapperObjectMapper<Ebusiness_WebSitesModule>();
        Configure<AbpAutoMapperOptions>(options =>
        {
            /* Uncomment `validate: true` if you want to enable the Configuration Validation feature.
             * See AutoMapper's documentation to learn what it is:
             * https://docs.automapper.org/en/stable/Configuration-validation.html
             */
            options.AddMaps<Ebusiness_WebSitesModule>(/* validate: true */);
        });
    }

    private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
    {
        //context.Services.AddCors(options =>
        //{
        //    options.AddDefaultPolicy(builder =>
        //    {
        //        builder
        //            .WithOrigins(
        //                configuration["App:CorsOrigins"]?
        //                    .Split(",", StringSplitOptions.RemoveEmptyEntries)
        //                    .Select(o => o.RemovePostFix("/"))
        //                    .ToArray() ?? Array.Empty<string>()
        //            )
        //            .WithAbpExposedHeaders()
        //            .SetIsOriginAllowedToAllowWildcardSubdomains()
        //            .AllowAnyHeader()
        //            .AllowAnyMethod()
        //            .AllowCredentials();
        //    });
        //});

        // 添加 CORS 服务，定义一个全开放策略
        context.Services.AddCors(options =>
        {
            options.AddPolicy("AllowVueClient", policy =>
            {
                policy
                    .WithOrigins("http://localhost:5173")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials(); // 如果有身份验证、cookie 等
            });
        });
    }

    private void ConfigureDataProtection(ServiceConfigurationContext context)
    {
        context.Services.AddDataProtection().SetApplicationName("Ebusiness_WebSites");
    }

    private void ConfigureEfCore(ServiceConfigurationContext context)
    {
        context.Services.AddAbpDbContext<Ebusiness_WebSitesDbContext>(options =>
        {
            /* You can remove "includeAllEntities: true" to create
             * default repositories only for aggregate roots
             * Documentation: https://docs.abp.io/en/abp/latest/Entity-Framework-Core#add-default-repositories
             */
            options.AddDefaultRepositories(includeAllEntities: true);
        });

        Configure<AbpDbContextOptions>(options =>
        {
            options.Configure(configurationContext =>
            {
                configurationContext.UseMySQL();
            });
        });

    }

    public override void OnApplicationInitialization(ApplicationInitializationContext context)
    {
        var app = context.GetApplicationBuilder();
        var env = context.GetEnvironment();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseAbpRequestLocalization();

        app.UseCorrelationId();
        app.UseStaticFiles();
        app.UseRouting();
        //app.UseCors();
        app.UseCors("AllowVueClient");
        app.UseAuthentication();


        app.UseUnitOfWork();
        app.UseDynamicClaims();
        app.UseAuthorization();

        app.UseSwagger();
        app.UseAbpSwaggerUI(options =>
        {
            options.SwaggerEndpoint("/swagger/v1/swagger.json", "Ebusiness_WebSites API");

            var configuration = context.GetConfiguration();
            options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
            options.OAuthScopes("OrderService");
        });

        app.UseAuditing();
        app.UseAbpSerilogEnrichers();
        app.UseConfiguredEndpoints();
    }
}
